package com.xbongbong.pro.statistics.strategy.chart.type.impl;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.bi.pojo.vo.DataSetResultVO;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.XbbConstant;
import com.xbongbong.paas.enums.AggTypeEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.pro.bi.commons.pojo.AggFieldPojo;
import com.xbongbong.pro.bi.commons.pojo.vo.GroupSqlVO;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.statistic.help.ChartResultHelp;
import com.xbongbong.pro.statistic.pojo.ChartFieldAttrPojo;
import com.xbongbong.pro.statistic.result.pojo.ChartResultPojo;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import com.xbongbong.pro.statistic.result.pojo.vo.ChartAnalysisVO;
import com.xbongbong.pro.statistics.help.ChartGraphVOHelper;
import com.xbongbong.pro.statistics.help.DescribeTableHelper;
import com.xbongbong.pro.statistics.help.DisplayHelper;
import com.xbongbong.pro.statistics.help.InitSqlHelper;
import com.xbongbong.pro.statistics.helper.AggHelper;
import com.xbongbong.pro.statistics.helper.ChartDataSetHelper;
import com.xbongbong.pro.statistics.pojo.dto.ChartAnalysisDTO;
import com.xbongbong.pro.statistics.pojo.dto.GenerateSqlDTO;
import com.xbongbong.pro.statistics.pojo.vo.GenerateSqlVO;
import com.xbongbong.pro.statistics.strategy.chart.type.ChartTypeStrategyService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 描述信息
 *
 * @ClassName ChartStrategyServiceImpl
 * @Author 梁鲁江
 * 创建时间 2022/9/21 15:42
 * 修改时间  2022/9/21 15:42
 **/
@Service
public class ChartStrategyServiceImpl implements ChartTypeStrategyService {
    @Resource
    private DisplayHelper displayHelper;
    @Resource
    private ChartResultHelp chartResultHelp;
    @Resource
    private DescribeTableHelper describeTableHelper;
    @Resource
    private ChartDataSetHelper chartDataSetHelper;
    @Resource
    private AggHelper aggHelper;
    @Resource
    private ChartGraphVOHelper chartGraphVOHelper;
    @Resource
    private InitSqlHelper initSqlHelper;
    @Override
    public ChartAnalysisVO chartAnalysis(ChartAnalysisDTO chartAnalysisDTO) throws XbbException {
        Map<String, Map<String, String>> attrLinkMap = aggHelper.getLinkMap(chartAnalysisDTO.getChartEntity(),  chartAnalysisDTO.getResultArray());
        return chartGraphVOHelper.chartGraphAnalysis(chartAnalysisDTO,attrLinkMap);
    }

    @Override
    public GenerateSqlVO generateSql(GenerateSqlDTO generateSqlDTO) throws XbbException {
        GenerateSqlVO generateSqlVO = new GenerateSqlVO();
        ChartEntity chartEntity = generateSqlDTO.getChartEntity();
        if (chartEntity.getChartClassify().size() <= 0 || chartEntity.getChartValue().size() <= 0) {
            return generateSqlVO;
        }
        ChartResultPojo chartResultPojo = generateSqlDTO.getChartResultPojo();
        //关联产品需要boardJson
        DataSetResultVO dataSetResultVO = chartDataSetHelper.getDataSetParseSql(generateSqlDTO, chartEntity);
        String parseSql = dataSetResultVO.getParseSql();
        Map<String, String> sortFieldMap = displayHelper.getAggSortMap(chartEntity, chartResultPojo.getSortStatisticsMap(),chartResultPojo.getSortFieldOrder());
        //查询条件和筛选条件放在一起
        String filter = describeTableHelper.filterField(chartEntity);
        //分组字段放在colums
        List<String> groupColumnsList = new ArrayList<>();
        //分组字段放在group by 
        List<String> groupFieldsList = new ArrayList<>();
        Map<String, AggFieldPojo>  aggFieldMap = new LinkedHashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> aggFieldsList = new ArrayList<>();
        List<String> sumTotalFieldsList = new ArrayList<>();
        List<String> subQuerySqlOfCountList = new ArrayList<>();
        List<String> summaryColumnAlisa = new ArrayList<>();
        FieldAttrPojo classifyAttr = JSONArray.parseArray(chartEntity.getChartClassify().toJSONString(), FieldAttrPojo.class).get(0);
        List<ChartFieldAttrPojo> valueAttrList = JSONArray.parseArray(chartEntity.getChartValue().toJSONString(), ChartFieldAttrPojo.class);
        List<ChartFieldAttrPojo> valueAttrSecondList = null;
        //保存下拉类型的字段
        Map<String,FieldAttrPojo> comboFieldMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionUtils.isNotEmpty(chartEntity.getChartValueSecond())){
            valueAttrSecondList = JSONArray.parseArray(chartEntity.getChartValueSecond().toJSONString(), ChartFieldAttrPojo.class);
        }
        //分类
        aggHelper.setGroupField(groupColumnsList, groupFieldsList, classifyAttr, comboFieldMap, chartEntity, sortFieldMap);
        //系列
        if (CollectionUtils.isNotEmpty(chartEntity.getChartSeries())) {
            FieldAttrPojo seriesAttr = JSONArray.parseArray(chartEntity.getChartSeries().toJSONString(), FieldAttrPojo.class).get(0);
            //系列设置字段
            aggHelper.setGroupField(groupColumnsList, groupFieldsList, seriesAttr, comboFieldMap, chartEntity, sortFieldMap);
            
        }
        for (ChartFieldAttrPojo fieldAttrPojo : valueAttrList) {
            AggTypeEnum aggTypeEnum = AggTypeEnum.getByAlias(fieldAttrPojo.getAggType());
            if(Objects.equals(fieldAttrPojo.getAttr(),PaasConstant.COUNT)){
                aggTypeEnum =  AggTypeEnum.COUNT;
            }
            String attr = fieldAttrPojo.getAttr();
            if (Objects.equals(FieldTypeEnum.COMPUTED_FIELD.getType(), fieldAttrPojo.getFieldType())) {
                aggHelper.addComputedField(chartEntity,PaasConstant.LEFT,aggFieldMap,aggFieldsList,fieldAttrPojo,aggTypeEnum,sumTotalFieldsList,subQuerySqlOfCountList,summaryColumnAlisa);
            } else {
                aggHelper.addValuesField(PaasConstant.LEFT, aggFieldMap, aggFieldsList, fieldAttrPojo, aggTypeEnum, attr,sortFieldMap, sumTotalFieldsList,summaryColumnAlisa);
            }
        }

        if (CollectionUtils.isNotEmpty(valueAttrSecondList)){
            for (ChartFieldAttrPojo fieldAttrPojo : valueAttrSecondList) {
                AggTypeEnum aggTypeEnum = AggTypeEnum.getByAlias(fieldAttrPojo.getAggType());
                if(Objects.equals(fieldAttrPojo.getAttr(),PaasConstant.COUNT)){
                    aggTypeEnum =  AggTypeEnum.COUNT;
                }
                String attr = fieldAttrPojo.getAttr();
                if (Objects.equals(FieldTypeEnum.COMPUTED_FIELD.getType(), fieldAttrPojo.getFieldType())) {
                    aggHelper.addComputedField(chartEntity,PaasConstant.RIGHT,aggFieldMap,aggFieldsList,fieldAttrPojo,aggTypeEnum,sumTotalFieldsList,subQuerySqlOfCountList,summaryColumnAlisa);
                } else {
                    aggHelper.addValuesField(PaasConstant.RIGHT, aggFieldMap, aggFieldsList, fieldAttrPojo, aggTypeEnum, attr,sortFieldMap, sumTotalFieldsList,summaryColumnAlisa);
                }
            }
        }

        GroupSqlVO groupSqlVO = GroupSqlVO.initGroupSqlVO(comboFieldMap, groupFieldsList);
        groupSqlVO.setSubQuerySqlOfCountList(subQuerySqlOfCountList);
        groupSqlVO.setSummaryColumnAlisa(summaryColumnAlisa);
        initSqlHelper.buildSubColumnOfCount(groupSqlVO,groupColumnsList,Boolean.FALSE);

        groupColumnsList.addAll(aggFieldsList);
        //","分割
        String colums = String.join(XbbConstant.SQL_COMMA, groupColumnsList);
        String groupFields = String.join(XbbConstant.SQL_COMMA, groupFieldsList);
        String sortField = displayHelper.getDsAggSortField(sortFieldMap,groupSqlVO);
        StringBuffer sql = chartDataSetHelper.tableSqlAppend(parseSql, colums, sortField, filter, 100, 0, groupFields, false,groupSqlVO);
        int pageSize =  XbbConstant.STATISTICS_PAGE_SIZE;
        PageHelper pageHelper = new PageHelper(chartResultPojo.getPage(), pageSize);
        generateSqlVO.setPageHelper(pageHelper);
        generateSqlVO.setStringBufferSql(sql);
        generateSqlVO.setAggFieldMap(aggFieldMap);
        return generateSqlVO;
    }
}
